package com.cndongtai.service.user;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.cndongtai.dao.impl.ChargeCountDao;
import com.cndongtai.dao.inter.MenuMapper;
import com.cndongtai.dao.inter.RoleMapper;
import com.cndongtai.dao.inter.RoleMenuMapper;
import com.cndongtai.dao.inter.UserMapper;
import com.cndongtai.dao.inter.UserRoleMapper;
import com.cndongtai.po.ChargeCount;
import com.cndongtai.po.Menu;
import com.cndongtai.po.Role;
import com.cndongtai.po.RoleMenu;
import com.cndongtai.po.User;
import com.cndongtai.po.UserRole;
import com.cndongtai.util.DateUtil;
import com.cndongtai.util.ValidateUtil;
import com.cndongtai.vo.RoleBean;
import com.cndongtai.vo.UserBean;

@Service("userService")
public class UserService {

	@Resource(name="userDao")
	private UserMapper userDao;
	
	@Resource(name="roleDao")
	private RoleMapper roleDao;
	
	@Resource(name="userRoleDao")
	private UserRoleMapper userRoleDao;
	
	@Resource(name="menuDao")
	private MenuMapper menuDao;
	
	@Resource(name="roleMenuDao")
	private RoleMenuMapper roleMenuDao;
	
	@Resource(name="chargeCountDao")
	private ChargeCountDao chargeCountDao;
	
	public User getUserInfoById(Long userId) {
		User user = userDao.queryByUserId(userId);
		return user;
	}
	
	public User getUserInfoByUsername(String username) {
		User user = userDao.queryByUsername(username);
		return user;
	}
	
	public List<UserRole> queryUserRoleList(Long userId) {
		return userRoleDao.queryUserRoleList(userId);
	}
	
	public String[] insertUser(User user) {
		String[] res = checkUser(user);
		if("11".equals(res[0])) {
			return res;
		}
		userDao.insertUser(user);
		res[0] = "00";
		res[1] = "添加成功";
		return res;
	}
	
	public String[] updateUser(User user) {
		String[] res = checkUpdateUser(user);
		if("11".equals(res[0])) {
			return res;
		}
		userDao.updateUser(user);
		res[0] = "00";
		res[1] = "修改成功";
		return res;
	}
	
	public boolean deleteUser(User user) {
		return userDao.deleteUser(user);
	}
	
	private String[] checkUpdateUser(User user) {
		String[] res = new String[2];
		User u = userDao.queryByUsername(user.getUsername());
		if(u!=null && !u.getUserId().equals(user.getUserId())) {
			res[0] = "11";
			res[1] = "用户名已存在";
			return res;
		}
		
		u = userDao.queryByMobile(user.getMobile());
		if(u!=null && !u.getUserId().equals(user.getUserId())) {
			res[0] = "11";
			res[1] = "该手机号已注册";
			return res;
		}
		
		res[0] = "00";
		res[1] = "";
		
		return res;
	}
	
	private String[] checkUser(User user) {
		String[] res = new String[2];
		User u = userDao.queryByUsername(user.getUsername());
		if(u!=null) {
			res[0] = "11";
			res[1] = "用户名已存在";
			return res;
		}
		
		u = userDao.queryByMobile(user.getMobile());
		if(u!=null) {
			res[0] = "11";
			res[1] = "该手机号已注册";
			return res;
		}
		
		res[0] = "00";
		res[1] = "";
		
		return res;
	}
	
	public List<User> queryUserList() {
		return userDao.queryUserList();
	}
	
	public List<UserBean> queryUserBeanList() {
		List<User> userList = userDao.queryUserList();
		List<UserBean> beanList = new ArrayList<UserBean>();
		
		if(userList!=null) {
			for(User user : userList) {
				beanList.add(convertUser2Bean(user));
			}
		}
		
		return beanList;
	}
	
	private UserBean convertUser2Bean(User user) {
		UserBean bean = new UserBean();
		
		bean.setUserId(user.getUserId());
		bean.setUsername(user.getUsername());
		bean.setCompany(user.getCompany());
		bean.setMobile(user.getMobile());
		bean.setRealName(user.getRealName());
		bean.setCreateTime(DateUtil.timeFormat(user.getCreateTime()));
		bean.setState(user.getState());
		bean.setEmail(user.getEmail());
		bean.setAddress(user.getAddress());
		bean.setRemark(user.getRemark());
		
		return bean;
	}
	
	public List<RoleBean> queryRoleBeanList() {
		List<RoleBean> beanList = new ArrayList<RoleBean>();
		List<Role> roleList = roleDao.queryRoleList();
		if(roleList!=null) {
			for(Role role : roleList) {
				beanList.add(convertRole2Bean(role));
			}
		}
		
		return beanList;
	}
	
	public RoleBean queryRoleBeanByRoleId(Long roleId) {
		Role role = roleDao.queryRoleById(roleId);
		RoleBean roleBean = convertRole2Bean(role);
		
		// 获取关联关系
		//roleMenuDao.queryRoleMenuByRoleId(roleId);
		
		return roleBean;
	}
	
	private RoleBean convertRole2Bean(Role role) {
		RoleBean bean = new RoleBean();
		
		bean.setRoleId(role.getRoleId());
		bean.setRoleName(role.getRoleName());
		bean.setRemark(role.getRemark());
		bean.setCreateTime(DateUtil.timeFormat(role.getCreateTime()));
		bean.setState(role.getState());
		
		return bean;
	}
	
	public String[] addRole(Role role) {
		String[] res = new String[2];
		if(ValidateUtil.empty(role.getRoleName())) {
			res[0] = "11";
			res[0] = "角色名称不能为空";
			return res;
		}
		
		if(roleDao.addRole(role)) {
			res[0] = "00";
			res[1] = "添加成功";
		}else {
			res[0] = "11";
			res[1] = "添加失败";
		}
		return res;
	}
	
	public String[] updateRole(Role role) {
		String[] res = new String[2];
		if(ValidateUtil.empty(role.getRoleName())) {
			res[0] = "11";
			res[0] = "角色名称不能为空";
			return res;
		}
		
		if(roleDao.updateRole(role)) {
			res[0] = "00";
			res[1] = "修改成功";
		}else {
			res[0] = "11";
			res[1] = "修改失败";
		}
		return res;
	}
	
	public List<Menu> queryMenuByUserId(Long userId) {
		List<Menu> menuList = new ArrayList<Menu>();
		List<UserRole> roleList = userRoleDao.queryUserRoleList(userId);
		if(roleList==null || roleList.size()==0) {
			return menuList;
		}
		
		for(UserRole role : roleList) {
			List<Menu> tempMenuList = menuDao.queryMenuList(role.getRoleId());
			menuList.addAll(tempMenuList);
		}
		
		return menuList;
	}
	
	public String queryMenuJsonTree(Long roleId) {
		StringBuffer jsonTree = new StringBuffer();
		jsonTree.append("[");
		List<Menu> menuList = menuDao.queryAllMenuList();
		if(menuList==null || menuList.size()==0) {
			jsonTree.append("]");
			return jsonTree.toString();
		}
		if(roleId!=null) {
			List<Menu> checkedMenuList = menuDao.queryMenuList(roleId);
			for(Menu menu: menuList) {
				if(menu.getMenuLevel()==1) {
					jsonTree.append(menuTree(menu, menuList,checkedMenuList));
				}
			}
		}else {
			for(Menu menu: menuList) {
				if(menu.getMenuLevel()==1) {
					jsonTree.append(menuTree(menu, menuList,null));
				}
			}
		}
		
		if(jsonTree.length() > 2) {
			jsonTree.deleteCharAt(jsonTree.length()-1);
		}
		
		jsonTree.append("]");
		
		return jsonTree.toString();
	}
	
	private String menuTree(Menu menu, List<Menu> menuList, List<Menu> checkedMenuList) {
		StringBuffer json = new StringBuffer();
		if(checkedMenuList==null) {
			json.append("{ id:").append(menu.getMenuId()).append(", pId:")
			.append(menu.getSuperId()).append(", name:'").append(menu.getMenuName())
			.append("', checked:false},");
			for(Menu child: menuList) {
				if(child.getSuperId()==menu.getMenuId()) {
					json.append(menuTree(child, menuList,null));
				}
			}
		}else {
			json.append("{ id:").append(menu.getMenuId()).append(", pId:")
			.append(menu.getSuperId()).append(", name:'").append(menu.getMenuName());
			
			String flag = "false";
			for(Menu checkedMenu : checkedMenuList) {
				if(menu.getMenuId()==checkedMenu.getMenuId()) {
					flag = "true";
				}
			}
			
			json.append("', checked:"+flag+"},");
			
			for(Menu child: menuList) {
				if(child.getSuperId()==menu.getMenuId()) {
					json.append(menuTree(child, menuList,null));
				}
			}
		}
		
		return json.toString();
	}
	
	
	public boolean addUserRole(List<UserRole> userRoleList) {
		for(UserRole userRole : userRoleList) {
			userRoleDao.addUserRole(userRole);
		}
		
		return true;
	}
	
	public boolean deleteUserRole(Long userId) {
		return userRoleDao.deleteUserRole(userId);
	}
	
	public boolean delRoleMenuBtRoleId(Long roleId) {
		return roleMenuDao.delRoleMenuByRoleId(roleId);
	}
	
	public boolean addRoleMenuList(List<RoleMenu> roleMenuList) {
		for(RoleMenu roleMenu : roleMenuList) {
			roleMenuDao.addRoleMenu(roleMenu);
		}
		
		return true;
	}
	
	public String queryCo2decreasedByUserId(Long userId) {
		
		DecimalFormat format = new DecimalFormat("0.##");
		
		ChargeCount chargeCount = chargeCountDao.queryChargeCountByUserId(userId);
		if(chargeCount==null) {
			return "0";
		}else {
			return format.format(chargeCount.getChargeCount()*1.11);
		}
	}
	
	public String queryCo2decreasedOrderByUserId(Long userId) {
		
		ChargeCount chargeCount = chargeCountDao.queryChargeCountByUserId(userId);
		if(chargeCount==null) {
			return "0";
		}else {
			return chargeCountDao.queryChargeCountOrder(chargeCount) + "";
		}
	}
}
